import { NextRequest, NextResponse } from 'next/server';
import { auth } from '@/auth';
import { prisma } from '@/lib/db';

// GET /api/projects/[id]/activities - 获取项目活动记录
export async function GET(
  request: NextRequest,
  context: { params: { id: string } }
) {
  try {
    const params = await context.params;
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const projectId = params.id;

    // 检查用户是否有权限访问该项目
    const hasAccess = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId,
        },
      },
    });

    if (!hasAccess) {
      return NextResponse.json({ error: '无权访问此项目' }, { status: 403 });
    }

    // 获取项目活动记录
    const activities = await prisma.activity.findMany({
      where: {
        projectId: params.id,
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
      take: 50, // 限制返回数量
    });

    // 获取项目信息，为示例活动提供必要信息
    const project = await prisma.project.findUnique({
      where: { id: projectId },
      include: {
        users: {
          include: { user: true }
        }
      }
    });

    // 如果没有找到活动记录，创建一些示例活动
    if (activities.length === 0 && project) {
      const now = new Date();
      const projectUser = project.users.find(pu => pu.role === 'OWNER') || project.users[0];
      const activityUser = projectUser?.user || { id: userId, name: session.user.name, image: session.user.image };
      
      // 创建5天内的示例活动
      const sampleActivities = [
        {
          id: `sample-${Date.now()}-1`,
          type: 'PROJECT_CREATED',
          userId: activityUser.id,
          projectId: projectId,
          entityId: projectId,
          createdAt: new Date(now.getTime() - 5 * 24 * 60 * 60 * 1000),
          data: {},
          user: {
            id: activityUser.id,
            name: activityUser.name,
            image: activityUser.image
          }
        },
        {
          id: `sample-${Date.now()}-2`,
          type: 'TASK_CREATED',
          userId: activityUser.id,
          projectId: projectId,
          entityId: `sample-task-${Date.now()}-1`,
          createdAt: new Date(now.getTime() - 4 * 24 * 60 * 60 * 1000),
          data: {
            task: {
              title: '创建项目需求文档'
            }
          },
          user: {
            id: activityUser.id,
            name: activityUser.name,
            image: activityUser.image
          }
        },
        {
          id: `sample-${Date.now()}-3`,
          type: 'STATUS_CHANGED',
          userId: activityUser.id,
          projectId: projectId,
          entityId: `sample-task-${Date.now()}-1`,
          createdAt: new Date(now.getTime() - 3 * 24 * 60 * 60 * 1000),
          data: {
            task: {
              title: '创建项目需求文档'
            },
            oldStatus: 'TODO',
            status: 'IN_PROGRESS'
          },
          user: {
            id: activityUser.id,
            name: activityUser.name,
            image: activityUser.image
          }
        },
        {
          id: `sample-${Date.now()}-4`,
          type: 'COMMENT_ADDED',
          userId: activityUser.id,
          projectId: projectId,
          entityId: `sample-task-${Date.now()}-1`,
          createdAt: new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000),
          data: {
            task: {
              title: '创建项目需求文档'
            },
            comment: '我已经完成了初稿，请大家检查一下'
          },
          user: {
            id: activityUser.id,
            name: activityUser.name,
            image: activityUser.image
          }
        },
        {
          id: `sample-${Date.now()}-5`,
          type: 'TASK_COMPLETED',
          userId: activityUser.id,
          projectId: projectId,
          entityId: `sample-task-${Date.now()}-1`,
          createdAt: new Date(now.getTime() - 1 * 24 * 60 * 60 * 1000),
          data: {
            task: {
              title: '创建项目需求文档'
            }
          },
          user: {
            id: activityUser.id,
            name: activityUser.name,
            image: activityUser.image
          }
        }
      ];

      return NextResponse.json({
        success: true,
        data: sampleActivities,
        isSample: true
      });
    }

    return NextResponse.json({
      success: true,
      data: activities,
    });
  } catch (error) {
    console.error('获取项目活动记录失败:', error);
    return NextResponse.json(
      { success: false, error: '获取项目活动记录失败' },
      { status: 500 }
    );
  }
}

// POST /api/projects/[id]/activities - 创建项目活动记录
export async function POST(
  request: NextRequest,
  context: { params: { id: string } }
) {
  try {
    const params = await context.params;
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const projectId = params.id;
    const data = await request.json();

    // 检查用户是否有权限访问该项目
    const hasAccess = await prisma.projectUser.findUnique({
      where: {
        userId_projectId: {
          userId,
          projectId,
        },
      },
    });

    if (!hasAccess) {
      return NextResponse.json({ error: '无权访问此项目' }, { status: 403 });
    }

    // 创建活动记录
    const activity = await prisma.activity.create({
      data: {
        type: data.type,
        userId: userId,
        project: {
          connect: {
            id: projectId
          }
        },
        entityId: data.entityId,
        data: data.meta || {},
      },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
          },
        },
      },
    });

    return NextResponse.json({
      success: true,
      data: activity,
    });
  } catch (error) {
    console.error('创建项目活动记录失败:', error);
    return NextResponse.json(
      { success: false, error: '创建项目活动记录失败' },
      { status: 500 }
    );
  }
} 